package com.xdf.ecommerce.filter;

import com.xdf.ecommerce.constant.GatewayConstant;
import com.xdf.ecommerce.utils.GatewayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 缓存请求 body 的全局过滤器
 * @author chanchaw
 * @create 2025-10-18 10:39
 */
@Slf4j
@Component
public class GlobalCacheRequestBodyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        boolean loginOrRegister = GatewayUtils.isLoginOrRegister(exchange.getRequest().getURI().getPath());
        // 没有设置请求头，不需要缓存 body 数据，直接退出
        if(null == exchange.getRequest().getHeaders().getContentType())
            return chain.filter(exchange);
        // 不是登录/注册请求，不需要缓存 body 数据，直接退出
        if(!loginOrRegister)
            return chain.filter(exchange);

        // 只有：登录/注册，两个请求需要缓存 body 数据
        return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
            DataBufferUtils.retain(dataBuffer);// 确保数据缓冲区不被释放
            // 使用当前数据创建副本
            Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0,dataBuffer.readableByteCount())));
            // 使用缓存的请求数据重新包装 ServerHttpRequest 并返回
            ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()){
                @Override
                public Flux<DataBuffer> getBody(){
                    return cachedFlux;
                }
            };

            return chain.filter(exchange.mutate().request(mutatedRequest).build());
        });
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 1;
    }
}
